package com.kehutong.employee.service;

import com.kehutong.common.DoveClient;
import com.kehutong.employee.dao.PositionDao;
import com.kehutong.employee.entity.Employee;
import com.kehutong.employee.entity.Position;
import com.kehutong.employee.enums.PositionType;
import org.coraframework.authz.HasPermission;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.Condition;
import org.coraframework.orm.jdbc.execute.QueryCondition;
import org.coraframework.util.Objects;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebService("/basic/position/service")
public class PositionService {

	static final Logger logger = LoggerFactory.getLogger(PositionService.class);

	@Inject
	private JdbcSession jdbcSession;
	@Inject
	private DoveClient doveClient;
	@Inject
	private PositionDao positionDao;

	@ReqMapping("/page")
	public Object page(JSONObject jsonObject) {
		Page<Position> page = jdbcSession.findPage(Position.class)
				.like(jsonObject, "name")
				.eq("deleted", false)
				.order("sort", "desc")
				.page(jsonObject)
				.exe();

		return Result.success(page);
	}

	@ReqMapping("/list")
	public Object list(JSONObject jsonObject) {
        List<Position> list = jdbcSession.findArray(Position.class)
				.like(jsonObject, "name")
				.eq("deleted", false)
				.order("sort", "desc")
				.exe();

        return Result.success(list);
	}

	@ReqMapping("/get")
	public Object get(Position role) {
		if (Objects.nonNull(role) && role.isDeleted()) {
			return Result.success();
		}
		return Result.success(role);
	}

	@Bean(newInstance = true, copy = true)
	@ReqMapping("/save")
	public Object save(Position role) {

		QueryCondition query = Condition.createQuery(false);
		Map<String,Object> rs = positionDao.getMaxSort(query);
		role.setSort(Integer.valueOf(rs.get("sort").toString()));

		jdbcSession.insert(role);

		return Result.success();
	}

	@Bean(copy = true)
	@ReqMapping("/update")
	public Object update(Position role) {
		jdbcSession.updateById(role);

		return Result.success();
	}

	@ReqMapping("/delete")
	public Object delete(Position position) {

		List<Employee> employees = jdbcSession.findArray(Employee.class)
				.like("positionNos", position.getId())
				.exe();

		if(Objects.nonEmpty(employees)){
			return Result.error(0, "该岗位还存在" + employees.size() +"名员工，请先移除员工后再操作。");
		}

		position.setDeleted(true);
		jdbcSession.updateById(position);

		return Result.success();
	}

	@ReqMapping("/updateSort")
	public Object updateSort(JSONObject jsonObject) {
		JSONArray array = jsonObject.getJSONArray("data");
		for (int i = 0; i < array.size(); i ++) {
			JSONObject json = array.getJSONObject(i);
			Position entity = Pool.get(Position.class, json.getString("id"));
			entity.setSort(json.getInteger("sort"));
			jdbcSession.updateById(entity);
		}
		return Result.success();
	}

	@ReqMapping("/tree")
	public Object tree(JSONObject jsonObject) {
		JSONObject root = new JSONObject();
		List<JSONObject> rootChildList = new ArrayList<>();
		for (PositionType type :PositionType.values()) {
			if(type == PositionType.POSITION){
				JSONObject item = new JSONObject();
				item.put("name", type.getDesc());
				item.put("isQurey", false);

				final List<Position> list = jdbcSession.findArray(Position.class)
						.like(jsonObject, "name")
						.order("createTime", "DESC")
						.exe();

				List<JSONObject> childList = list.stream().map(entity -> {
					JSONObject temp = new JSONObject();
					temp.put("name", entity.getName());
					temp.put("position", entity.getId());
					temp.put("isQurey", true);
					return temp;
				}).collect(Collectors.toList());

				item.put("childList", childList);
				rootChildList.add(item);
			}else{
				JSONObject item = new JSONObject();
				item.put("name", type.getDesc());
				item.put("isQurey", false);

				JSONObject entity = new JSONObject();
				entity.put("name", "管家/上级");
				entity.put("identity", "1");
				entity.put("isQurey", true);

				item.put("childList", Arrays.asList(entity));
				rootChildList.add(item);
			}
		}
		root.put("childList", rootChildList);

		return Result.success(root);
	}

}
